// 关卡管理系统
const LEVELS = {
    // 关卡配置
    configs: [
        // 第1关
        {
            level: 1,
            enemyCount: 5,
            enemyTypes: [
                { type: 'regular', count: 5 }
            ],
            timeLimit: 120,
            map: 'urban',
            spawnPoints: [
                { x: -20, y: 0, z: -20 },
                { x: 20, y: 0, z: -20 },
                { x: -20, y: 0, z: 20 },
                { x: 20, y: 0, z: 20 },
                { x: 0, y: 0, z: -30 }
            ],
            objectives: [
                { type: 'kill_enemies', count: 5, description: '消灭所有敌人' },
                { type: 'survive', time: 60, description: '生存60秒' }
            ],
            difficulty: 'easy',
            rewards: {
                score: 1000,
                unlock: 'shotgun'
            }
        },
        // 第2关
        {
            level: 2,
            enemyCount: 8,
            enemyTypes: [
                { type: 'regular', count: 5 },
                { type: 'fast', count: 3 }
            ],
            timeLimit: 150,
            map: 'urban',
            spawnPoints: [
                { x: -25, y: 0, z: -25 },
                { x: 25, y: 0, z: -25 },
                { x: -25, y: 0, z: 25 },
                { x: 25, y: 0, z: 25 },
                { x: 0, y: 0, z: -35 },
                { x: -35, y: 0, z: 0 },
                { x: 35, y: 0, z: 0 },
                { x: 0, y: 0, z: 35 }
            ],
            objectives: [
                { type: 'kill_enemies', count: 8, description: '消灭所有敌人' },
                { type: 'kill_fast_enemies', count: 3, description: '消灭3个快速敌人' }
            ],
            difficulty: 'easy',
            rewards: {
                score: 1500,
                unlock: 'speed_skill'
            }
        },
        // 第3关
        {
            level: 3,
            enemyCount: 11,
            enemyTypes: [
                { type: 'regular', count: 6 },
                { type: 'fast', count: 3 },
                { type: 'tank', count: 2 }
            ],
            timeLimit: 180,
            map: 'mountain',
            spawnPoints: [
                { x: -30, y: 0, z: -30 },
                { x: 30, y: 0, z: -30 },
                { x: -30, y: 0, z: 30 },
                { x: 30, y: 0, z: 30 },
                { x: -40, y: 0, z: 0 },
                { x: 40, y: 0, z: 0 },
                { x: 0, y: 0, z: -40 },
                { x: 0, y: 0, z: 40 },
                { x: -20, y: 0, z: -40 },
                { x: 20, y: 0, z: -40 },
                { x: -20, y: 0, z: 40 }
            ],
            objectives: [
                { type: 'kill_enemies', count: 11, description: '消灭所有敌人' },
                { type: 'kill_tank_enemies', count: 2, description: '消灭2个坦克敌人' },
                { type: 'survive', time: 120, description: '生存120秒' }
            ],
            difficulty: 'medium',
            rewards: {
                score: 2000,
                unlock: 'machinegun'
            }
        },
        // 第4关
        {
            level: 4,
            enemyCount: 14,
            enemyTypes: [
                { type: 'regular', count: 6 },
                { type: 'fast', count: 6 },
                { type: 'tank', count: 2 }
            ],
            timeLimit: 200,
            map: 'mountain',
            spawnPoints: [
                { x: -35, y: 0, z: -35 },
                { x: 35, y: 0, z: -35 },
                { x: -35, y: 0, z: 35 },
                { x: 35, y: 0, z: 35 },
                { x: -45, y: 0, z: 0 },
                { x: 45, y: 0, z: 0 },
                { x: 0, y: 0, z: -45 },
                { x: 0, y: 0, z: 45 },
                { x: -25, y: 0, z: -45 },
                { x: 25, y: 0, z: -45 },
                { x: -25, y: 0, z: 45 },
                { x: 25, y: 0, z: 45 },
                { x: -45, y: 0, z: -25 },
                { x: 45, y: 0, z: -25 }
            ],
            objectives: [
                { type: 'kill_enemies', count: 14, description: '消灭所有敌人' },
                { type: 'kill_fast_enemies', count: 6, description: '消灭6个快速敌人' }
            ],
            difficulty: 'medium',
            rewards: {
                score: 2500,
                unlock: 'heal_skill'
            }
        },
        // 第5关（BOSS关）
        {
            level: 5,
            enemyCount: 13,
            enemyTypes: [
                { type: 'regular', count: 6 },
                { type: 'fast', count: 4 },
                { type: 'tank', count: 2 },
                { type: 'boss', count: 1 }
            ],
            timeLimit: 300,
            map: 'factory',
            spawnPoints: [
                // 小兵出生点
                { x: -40, y: 0, z: -40 },
                { x: 40, y: 0, z: -40 },
                { x: -40, y: 0, z: 40 },
                { x: 40, y: 0, z: 40 },
                { x: -50, y: 0, z: 0 },
                { x: 50, y: 0, z: 0 },
                { x: 0, y: 0, z: -50 },
                { x: 0, y: 0, z: 50 },
                { x: -30, y: 0, z: -50 },
                { x: 30, y: 0, z: -50 },
                { x: -30, y: 0, z: 50 },
                { x: 30, y: 0, z: 50 },
                // BOSS出生点
                { x: 0, y: 0, z: 0 }
            ],
            objectives: [
                { type: 'kill_boss', count: 1, description: '击败BOSS' },
                { type: 'kill_enemies', count: 13, description: '消灭所有敌人' }
            ],
            difficulty: 'hard',
            rewards: {
                score: 5000,
                unlock: 'sniper',
                unlockSkill: 'damage_skill'
            }
        },
        // 第6关
        {
            level: 6,
            enemyCount: 17,
            enemyTypes: [
                { type: 'regular', count: 8 },
                { type: 'fast', count: 6 },
                { type: 'tank', count: 3 }
            ],
            timeLimit: 240,
            map: 'factory',
            spawnPoints: generateRandomSpawnPoints(17, 60),
            objectives: [
                { type: 'kill_enemies', count: 17, description: '消灭所有敌人' },
                { type: 'survive', time: 180, description: '生存180秒' }
            ],
            difficulty: 'hard',
            rewards: {
                score: 3000
            }
        },
        // 第7关
        {
            level: 7,
            enemyCount: 20,
            enemyTypes: [
                { type: 'regular', count: 8 },
                { type: 'fast', count: 8 },
                { type: 'tank', count: 4 }
            ],
            timeLimit: 260,
            map: 'space',
            spawnPoints: generateRandomSpawnPoints(20, 70),
            objectives: [
                { type: 'kill_enemies', count: 20, description: '消灭所有敌人' },
                { type: 'kill_tank_enemies', count: 4, description: '消灭4个坦克敌人' }
            ],
            difficulty: 'hard',
            rewards: {
                score: 3500
            }
        },
        // 第8关
        {
            level: 8,
            enemyCount: 23,
            enemyTypes: [
                { type: 'regular', count: 9 },
                { type: 'fast', count: 9 },
                { type: 'tank', count: 5 }
            ],
            timeLimit: 280,
            map: 'space',
            spawnPoints: generateRandomSpawnPoints(23, 75),
            objectives: [
                { type: 'kill_enemies', count: 23, description: '消灭所有敌人' },
                { type: 'kill_fast_enemies', count: 9, description: '消灭9个快速敌人' }
            ],
            difficulty: 'very_hard',
            rewards: {
                score: 4000
            }
        },
        // 第9关
        {
            level: 9,
            enemyCount: 26,
            enemyTypes: [
                { type: 'regular', count: 10 },
                { type: 'fast', count: 10 },
                { type: 'tank', count: 6 }
            ],
            timeLimit: 300,
            map: 'urban',
            spawnPoints: generateRandomSpawnPoints(26, 80),
            objectives: [
                { type: 'kill_enemies', count: 26, description: '消灭所有敌人' },
                { type: 'survive', time: 240, description: '生存240秒' }
            ],
            difficulty: 'very_hard',
            rewards: {
                score: 4500
            }
        },
        // 第10关（终极BOSS关）
        {
            level: 10,
            enemyCount: 25,
            enemyTypes: [
                { type: 'regular', count: 10 },
                { type: 'fast', count: 8 },
                { type: 'tank', count: 6 },
                { type: 'boss', count: 1 }
            ],
            timeLimit: 400,
            map: 'space',
            spawnPoints: generateRandomSpawnPoints(25, 85),
            objectives: [
                { type: 'kill_boss', count: 1, description: '击败终极BOSS' },
                { type: 'kill_enemies', count: 25, description: '消灭所有敌人' }
            ],
            difficulty: 'extreme',
            rewards: {
                score: 10000,
                unlock: 'god_mode',
                title: '终极战士'
            }
        }
    ],
    
    // 获取指定关卡的配置
    getLevelConfig: function(levelNumber) {
        return this.configs.find(config => config.level === levelNumber) || null;
    },
    
    // 获取关卡总数
    getTotalLevels: function() {
        return this.configs.length;
    },
    
    // 检查关卡是否存在
    hasLevel: function(levelNumber) {
        return this.configs.some(config => config.level === levelNumber);
    },
    
    // 根据难度获取关卡列表
    getLevelsByDifficulty: function(difficulty) {
        return this.configs.filter(config => config.difficulty === difficulty);
    },
    
    // 获取下一关
    getNextLevel: function(currentLevel) {
        const nextLevel = currentLevel + 1;
        return this.hasLevel(nextLevel) ? nextLevel : null;
    },
    
    // 获取关卡的难度描述
    getDifficultyDescription: function(difficulty) {
        const descriptions = {
            'easy': '简单',
            'medium': '中等',
            'hard': '困难',
            'very_hard': '非常困难',
            'extreme': '极限'
        };
        return descriptions[difficulty] || difficulty;
    },
    
    // 生成关卡的敌人
    generateEnemiesForLevel: function(levelNumber) {
        const config = this.getLevelConfig(levelNumber);
        if (!config) return [];
        
        const enemies = [];
        let spawnPointIndex = 0;
        
        // 根据配置生成不同类型的敌人
        config.enemyTypes.forEach(typeConfig => {
            for (let i = 0; i < typeConfig.count; i++) {
                const enemy = new Enemy(typeConfig.type);
                
                // 设置出生点
                if (spawnPointIndex < config.spawnPoints.length) {
                    const spawnPoint = config.spawnPoints[spawnPointIndex];
                    enemy.position.set(spawnPoint.x, spawnPoint.y + 0.5, spawnPoint.z);
                    spawnPointIndex++;
                } else {
                    // 如果没有足够的出生点，使用随机位置
                    enemy.position.set(
                        (Math.random() - 0.5) * 100,
                        0.5,
                        (Math.random() - 0.5) * 100
                    );
                }
                
                enemies.push(enemy);
            }
        });
        
        return enemies;
    },
    
    // 检查关卡完成条件
    checkLevelCompletion: function(levelNumber, playerStats, enemyStats) {
        const config = this.getLevelConfig(levelNumber);
        if (!config) return false;
        
        // 检查所有目标是否完成
        for (const objective of config.objectives) {
            let isCompleted = false;
            
            switch(objective.type) {
                case 'kill_enemies':
                    isCompleted = enemyStats.totalKilled >= objective.count;
                    break;
                case 'kill_fast_enemies':
                    isCompleted = enemyStats.fastKilled >= objective.count;
                    break;
                case 'kill_tank_enemies':
                    isCompleted = enemyStats.tankKilled >= objective.count;
                    break;
                case 'kill_boss':
                    isCompleted = enemyStats.bossKilled >= objective.count;
                    break;
                case 'survive':
                    isCompleted = playerStats.timeSurvived >= objective.time;
                    break;
            }
            
            if (!isCompleted) {
                return false;
            }
        }
        
        return true;
    },
    
    // 获取关卡奖励
    getLevelRewards: function(levelNumber) {
        const config = this.getLevelConfig(levelNumber);
        return config ? config.rewards : null;
    }
};

// 辅助函数：生成随机出生点
function generateRandomSpawnPoints(count, radius) {
    const spawnPoints = [];
    
    for (let i = 0; i < count; i++) {
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * radius * 0.8 + radius * 0.2; // 确保出生点不会太靠近中心
        
        spawnPoints.push({
            x: Math.cos(angle) * distance,
            y: 0,
            z: Math.sin(angle) * distance
        });
    }
    
    return spawnPoints;
}

// 关卡进度管理器
class LevelProgress {
    constructor() {
        this.completedLevels = [];
        this.bestScores = {};
        this.fastestTimes = {};
        this.totalScore = 0;
        
        this.loadProgress();
    }
    
    // 记录关卡完成
    recordLevelComplete(levelNumber, score, timeSpent) {
        if (!this.completedLevels.includes(levelNumber)) {
            this.completedLevels.push(levelNumber);
        }
        
        // 更新最高分
        if (!this.bestScores[levelNumber] || score > this.bestScores[levelNumber]) {
            this.bestScores[levelNumber] = score;
        }
        
        // 更新最快时间
        if (!this.fastestTimes[levelNumber] || timeSpent < this.fastestTimes[levelNumber]) {
            this.fastestTimes[levelNumber] = timeSpent;
        }
        
        this.totalScore += score;
        this.saveProgress();
    }
    
    // 获取下一个可玩关卡
    getNextPlayableLevel() {
        const sortedLevels = [...this.completedLevels].sort((a, b) => a - b);
        
        if (sortedLevels.length === 0) {
            return 1;
        }
        
        const lastCompleted = sortedLevels[sortedLevels.length - 1];
        if (LEVELS.hasLevel(lastCompleted + 1)) {
            return lastCompleted + 1;
        }
        
        return lastCompleted; // 已经完成所有关卡
    }
    
    // 保存进度到本地存储
    saveProgress() {
        try {
            const progress = {
                completedLevels: this.completedLevels,
                bestScores: this.bestScores,
                fastestTimes: this.fastestTimes,
                totalScore: this.totalScore
            };
            localStorage.setItem('cs_game_progress', JSON.stringify(progress));
        } catch (error) {
            console.error('保存进度失败:', error);
        }
    }
    
    // 从本地存储加载进度
    loadProgress() {
        try {
            const savedProgress = localStorage.getItem('cs_game_progress');
            if (savedProgress) {
                const progress = JSON.parse(savedProgress);
                this.completedLevels = progress.completedLevels || [];
                this.bestScores = progress.bestScores || {};
                this.fastestTimes = progress.fastestTimes || {};
                this.totalScore = progress.totalScore || 0;
            }
        } catch (error) {
            console.error('加载进度失败:', error);
        }
    }
    
    // 重置进度
    resetProgress() {
        this.completedLevels = [];
        this.bestScores = {};
        this.fastestTimes = {};
        this.totalScore = 0;
        this.saveProgress();
    }
}